const isFun = function (fun) {
  return typeof fun === 'function'
}
class Observer {
  constructor() {
    this.messageCollector = {}
    this.history = {}
  }
  on(...arg) {
    const [type, callback] = arg
    if (!isFun(callback)) {
      throw new TypeError(`callback of arguments for function ${this.subscribe.name} must be a function,try again`)
    }
    if (!this.messageCollector[type]) this.messageCollector[type] = []
    this.messageCollector[type].push(callback)
    return this
  }
  emit(...arg) {
    const [type, ...theme] = arg
    const subscribes = this.messageCollector[type] || []
    if (!this.history[type]) this.history[type] = []
    this.history[type].push(theme)
    for (const callback of subscribes) {
      callback.apply(this, theme)
    }
    return this
  }
  off(...arg) {
    const [type, callback] = arg
    if (!this.messageCollector[type] || !this.messageCollector[type].length) return
    if (!isFun(callback)) {
      throw new TypeError(`callback of arguments for function ${this.subscribe.name} must be a function `)
    }
    const subscribes = this.messageCollector[type]
    subscribes.some((item, index, arr) => {
      if (item === callback) {
        arr.splice(index, 1)
        return true
      }
    })
    return this
  }
  viewLog(...arg) {
    const [type, callback] = arg
    if (!this.history[type] || !isFun(callback)) return
    const themes = this.history[type]
    for (const theme of themes) {
      callback.apply(this, theme)
    }
    return this
  }
  reset() {
    this.messageCollector = {}
    this.history = {}
    return this
  }
}

let ob = new Observer()
ob.emit('click',
  `
    夕阳漫不经心走下酒坊
    晚风路过陶坛吹散了酒香
    偷倒空的酒坛还挂在墙上
    猫咪抱着尾巴睡得好安详
    我记得你所有的模样
  `
)
let sub1 = (data) => {
  console.log(data)
}
ob.on('click', sub1, 1)
ob.viewLog('click', (log) => {
  console.log(`publish_log: ${ log }`)
})
